import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/control_room/check_in_room.dart';
import 'package:thal/backstage/control_room/badge_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';

part 'check_in_production.page.dart';

/// 打卡页面
@PagePath('/check-in')
class CheckInProduction extends StatefulWidget {
  const CheckInProduction({super.key});

  @pageRouteQuery
  static const query = _$CheckInProductionQuery();

  @override
  State<CheckInProduction> createState() => _CheckInProductionState();
}

class _CheckInProductionState extends State<CheckInProduction> {
  late UserRoom _userRoom;
  late CheckInRoom _checkInRoom;
  late BadgeRoom _badgeRoom;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _userRoom = GlobalStateProvider.userRoomOf(context);
    _checkInRoom = GlobalStateProvider.checkInRoomOf(context);
    _badgeRoom = GlobalStateProvider.badgeRoomOf(context);
  }

  /// 计算连续签到天数
  int _calculateConsecutiveDays(String userId) {
    final now = DateTime.now();
    int consecutiveDays = 0;

    for (int i = 0; i < 365; i++) {
      final checkDate = now.subtract(Duration(days: i));
      final targetDate = DateTime(
        checkDate.year,
        checkDate.month,
        checkDate.day,
      );

      if (_checkInRoom.hasCheckedInOnDate(userId, targetDate)) {
        consecutiveDays++;
      } else {
        break; // 遇到未打卡的日期，停止计算
      }
    }

    return consecutiveDays;
  }

  /// 获取周几对应的日期
  DateTime _getWeekdayDate(int weekdayIndex) {
    final now = DateTime.now();
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));
    return startOfWeek.add(Duration(days: weekdayIndex));
  }

  /// 判断是否为同一天
  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  /// 处理打卡
  void _handleCheckIn() {
    final currentUser = _userRoom.fetchCurrentUser();
    if (currentUser == null) {
      return;
    }

    final success = _checkInRoom.performCheckIn(currentUser.id);

    if (success) {
      final consecutiveDays = _calculateConsecutiveDays(currentUser.id);

      // 检查是否应该获得徽章
      if (consecutiveDays == 1 && !_badgeRoom.hasBadge(currentUser.id, '1')) {
        _badgeRoom.awardBadge(currentUser.id, '1');
      } else if (consecutiveDays == 15 &&
          !_badgeRoom.hasBadge(currentUser.id, '4')) {
        _badgeRoom.awardBadge(currentUser.id, '4');
      } else if (consecutiveDays == 30 &&
          !_badgeRoom.hasBadge(currentUser.id, '5')) {
        _badgeRoom.awardBadge(currentUser.id, '5');
      }

      StageWhisper.cheer('Check-in successful!');
      setState(() {});
    } else {
      StageWhisper.caution('You have already checked in today');
    }
  }

  /// 构建单天状态
  Widget _buildDayStatus(String dayName, DateTime dayDate, int index) {
    final now = DateTime.now();
    final isToday = _isSameDay(dayDate, now);
    final isPast = dayDate.isBefore(now) && !isToday;

    return Observer(
      builder: (context) {
        bool isChecked = false;
        final currentUser = _userRoom.fetchCurrentUser();
        if (currentUser != null && (isPast || isToday)) {
          isChecked = _checkInRoom.hasCheckedInOnDate(currentUser.id, dayDate);
        }

        // 确定外层盒子背景颜色和圆形背景颜色（根据日期类型）
        Color containerBgColor;
        Color circleBgColor;
        Color dateTextColor;

        if (isPast) {
          // 过去日期：白色背景，蓝色圆圈
          containerBgColor = ColorPalette.blue3;
          circleBgColor = ColorPalette.white;
          dateTextColor = ColorPalette.white;
        } else if (isToday) {
          // 今天：白色背景，蓝色圆圈
          containerBgColor = ColorPalette.blue3;
          circleBgColor = ColorPalette.white;
          dateTextColor = ColorPalette.white;
        } else {
          // 未来日期：浅蓝色背景，白色圆圈
          containerBgColor = ColorPalette.blue2;
          circleBgColor = ColorPalette.white;
          dateTextColor = ColorPalette.white;
        }

        return Container(
          padding: EdgeInsets.all(3.w),
          decoration: ShapeDecoration(
            color: containerBgColor,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(21.r),
            ),
          ),
          child: Column(
            children: [
              8.h.heightBox,
              // 顶部星期
              Text(dayName)
                  .fontSize(14.sp)
                  .textColor(dateTextColor)
                  .arimo(weight: FontWeight.w700),
              2.h.heightBox,
              // 底部圆形状态
              Container(
                width: 36.w,
                height: 36.w,
                padding: EdgeInsets.all(6.w),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: circleBgColor,
                ),
                child: Center(
                  child:
                      isChecked
                          ? Image.asset(
                            AssetManifest.check,
                            color: ColorPalette.blue3,
                          )
                          : isPast && !isChecked
                          ? Image.asset(
                            AssetManifest.uncheck,
                            color: ColorPalette.blue3,
                          )
                          : Text('${dayDate.day}')
                              .fontSize(16.sp)
                              .textColor(ColorPalette.blue2)
                              .arimo(weight: FontWeight.w700),
                ),
              ),
              2.h.heightBox,
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopBar(),

              // 主要内容
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      70.h.heightBox,
                      // 顶部区域
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.only(left: 16.w),
                          child: _buildTopSection(),
                        ),
                      ),
                      32.h.heightBox,
                      // 每日签到卡片（包含吉祥物背景）
                      _buildDailyCheckInCard(),
                      20.h.heightBox,
                      // 连续签到进度卡片
                      _buildConsecutiveProgressCard(),
                      20.h.heightBox,
                      // 徽章展示
                      _buildBadgesSection(),
                      32.h.heightBox,
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 30.sp,
              ),
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text('Sign In')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),

          36.w.widthBox,
        ],
      ),
    );
  }

  /// 构建顶部区域：打卡按钮
  Widget _buildTopSection() {
    return Observer(
      builder: (context) {
        final currentUser = _userRoom.fetchCurrentUser();
        if (currentUser == null) return SizedBox.shrink();

        final hasCheckedIn = _checkInRoom.hasCheckedInToday(currentUser.id);

        return Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors:
                      hasCheckedIn
                          ? [ColorPalette.blue1, ColorPalette.blue2]
                          : [ColorPalette.blue1, ColorPalette.blue2],
                ),
                borderRadius: BorderRadius.circular(25.r),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.check_circle_outline,
                    size: 20.sp,
                    color: ColorPalette.white,
                  ),
                  2.w.widthBox,
                  Text(hasCheckedIn ? 'Checked' : 'Sign In')
                      .fontSize(16.sp)
                      .textColor(Colors.white)
                      .arimo(weight: FontWeight.w700),
                ],
              ),
            ).withTapEffect(onTap: _handleCheckIn),
          ],
        );
      },
    );
  }

  /// 构建每日签到卡片
  Widget _buildDailyCheckInCard() {
    return Observer(
      builder: (context) {
        final currentUser = _userRoom.fetchCurrentUser();
        if (currentUser == null) return SizedBox.shrink();

        final consecutiveDays = _calculateConsecutiveDays(currentUser.id);
        final weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              // 吉祥物
              Positioned(
                bottom: 20.h,
                right: -28.w,
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    // 熊猫图片
                    Image.asset(
                      AssetManifest.panda,
                      width: 293.w,
                      height: 293.w,
                      fit: BoxFit.contain,
                    ),
                  ],
                ),
              ),

              // 打卡卡片
              AspectRatio(
                aspectRatio: 358 / 164,
                child: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(AssetManifest.checkInCard),
                      fit: BoxFit.cover,
                    ),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(14.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        15.h.heightBox,
                        // 标题
                        Row(
                          children: [
                            Text('Check-In for ')
                                .fontSize(20.sp)
                                .textColor(ColorPalette.blue1)
                                .arimo(weight: FontWeight.w700),
                            Text(
                              '$consecutiveDays ',
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: ColorPalette.blue1,
                                fontWeight: FontWeight.w700,
                                decoration: TextDecoration.underline,
                                decorationColor: ColorPalette.blue1,
                              ),
                            ),
                            Text('days')
                                .fontSize(20.sp)
                                .textColor(ColorPalette.blue1)
                                .arimo(weight: FontWeight.w700),
                          ],
                        ),

                        Spacer(),

                        // 一周七天状态
                        Row(
                          children:
                              weekdays.asMap().entries.map((entry) {
                                final index = entry.key;
                                final dayName = entry.value;
                                final dayDate = _getWeekdayDate(index);

                                return Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.only(
                                      right:
                                          index < weekdays.length - 1 ? 4.w : 0,
                                    ),
                                    child: _buildDayStatus(
                                      dayName,
                                      dayDate,
                                      index,
                                    ),
                                  ),
                                );
                              }).toList(),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 计算进度条右侧位置
  /// 根据连续打卡天数计算进度，最大30天
  double _calculateProgressRight(int consecutiveDays) {
    // 计算已完成进度的比例 (连续天数 / 30)
    final progress = consecutiveDays / 30.0;

    // 进度条总宽度约为 303.w (351 - 48, 左右各24的padding)
    // 假设卡片宽度为351，减去左右边距15，约321w的可用空间
    const totalProgressWidth = 321.0;

    // 计算剩余的右边距
    final remainingRight = totalProgressWidth * (1 - progress);

    // 返回右边距，最小为15.w
    return remainingRight > 15.0 ? remainingRight : 15.0;
  }

  /// 构建连续签到进度卡片
  Widget _buildConsecutiveProgressCard() {
    return Observer(
      builder: (context) {
        final currentUser = _userRoom.fetchCurrentUser();
        if (currentUser == null) return SizedBox.shrink();

        final consecutiveDays = _calculateConsecutiveDays(currentUser.id);
        final hasDay1 = consecutiveDays >= 1;
        final hasDay15 = consecutiveDays >= 15;
        final hasDay30 = consecutiveDays >= 30;

        return AspectRatio(
          aspectRatio: 351 / 122,
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 11.h),
            decoration: BoxDecoration(
              color: ColorPalette.white,
              borderRadius: BorderRadius.circular(15.r),
              boxShadow: [
                BoxShadow(
                  color: ColorPalette.black.withValues(alpha: 0.1),
                  blurRadius: 20,
                  offset: Offset(0, 4.h),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 标题
                Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: 'Sign in consecutively to obtain ',
                        style: TextStyle(
                          fontSize: 15.sp,
                          color: ColorPalette.blue1,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      TextSpan(
                        text: 'a limited badge',
                        style: TextStyle(
                          fontSize: 15.sp,
                          color: ColorPalette.black,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ],
                  ),
                  textAlign: TextAlign.center,
                ),

                16.h.heightBox,

                // 进度条
                Expanded(
                  child: Stack(
                    children: [
                      // 整体的背景进度线（浅蓝色）
                      Positioned(
                        top: 15.h,
                        left: 15.w,
                        right: 15.w,
                        child: Container(
                          height: 3.h,
                          decoration: BoxDecoration(
                            color: ColorPalette.blue2,
                            borderRadius: BorderRadius.circular(2.r),
                          ),
                        ),
                      ),

                      // 已完成部分的进度线（深蓝色）
                      if (hasDay1)
                        Positioned(
                          top: 15.h,
                          left: 15.w,
                          right: _calculateProgressRight(consecutiveDays),
                          child: Container(
                            height: 3.h,
                            decoration: BoxDecoration(
                              color: ColorPalette.blue1,
                              borderRadius: BorderRadius.circular(2.r),
                            ),
                          ),
                        ),

                      // 进度点
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildProgressPoint('1st day', hasDay1),
                          _buildProgressPoint('15th day', hasDay15),
                          _buildProgressPoint('30th day', hasDay30),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建进度点
  Widget _buildProgressPoint(String label, bool achieved) {
    return Column(
      children: [
        Container(
          width: 30.w,
          height: 30.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: achieved ? ColorPalette.blue2 : ColorPalette.blue2,
            border:
                achieved
                    ? Border.all(color: ColorPalette.blue1, width: 2.w)
                    : null,
          ),
          child: Center(
            child:
                achieved
                    ? Image.asset(
                      AssetManifest.check,
                      width: 15.w,
                      height: 15.w,
                      color: ColorPalette.white,
                    )
                    : SizedBox.shrink(),
          ),
        ),
        4.h.heightBox,
        Text(label)
            .fontSize(10.sp)
            .textColor(ColorPalette.blue1)
            .arimo(weight: FontWeight.w700),
      ],
    );
  }

  /// 构建徽章展示区域
  Widget _buildBadgesSection() {
    return Observer(
      builder: (context) {
        final badges = _badgeRoom.fetchAllBadges();

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 徽章标题（可选）
              SizedBox.shrink(),

              // 徽章网格
              Row(
                children: [Expanded(child: _buildBadgeGrid(badges))],
              ).wrapHorizontal(40.w),

              // 说明文字
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    constraints: BoxConstraints(maxWidth: 250.w),
                    child: Center(
                      child:
                          Text(
                            'Sign in consecutively to obtain a limited badge. On the 1st, 15th, and 30th days respectively, you can each receive a separate badge',
                            textAlign: TextAlign.center,
                            style: TextStyle(height: 1.5),
                          ).fontSize(10.sp).textColor(ColorPalette.black).arimo(),
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建徽章网格
  Widget _buildBadgeGrid(List badges) {
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 12.w,
        crossAxisSpacing: 48.w,
      ),
      itemCount: badges.length,
      itemBuilder: (context, index) {
        final badge = badges[index];
        return SizedBox(
          child: ClipOval(
            child: Image.asset(
              badge.imageUrl,
              width: 50.w,
              height: 50.w,
              fit: BoxFit.contain,
            ),
          ),
        );
      },
    );
  }
}
